from aip import AipFace
import base64
import os,shutil

APP_ID = '26740821'
API_KEY= 'lyR2jTTgaUdoCw4BpMaih2nv'
SECRET_KEY = 'Z6lQP9Bw6nfSBwln5FeS9BjN8F9BlBT8'

client = AipFace(APP_ID, API_KEY, SECRET_KEY)
image_to_base64=lambda x: base64.b64encode(open(x, "rb").read()).decode()

def detect_faces(image):
    image_type = "BASE64"
    options = {"face_field": "age,beauty,expression,face_shape,gender", "max_face_num": 10}
    result = client.detect(image, image_type, options)
    if result['error_code'] == 0:
        return result['result']['face_list']
    return []

def face_match(main_image, target_image):
    """人脸对比"""
    target_faces = detect_faces(target_image)
    if not target_faces:
        print("目标图片中没有检测到人脸")
        return False
    
    group_faces = detect_faces(main_image)
    for face in group_faces:
        result = client.match([
            {
                "image": target_image,
                "image_type": "BASE64",
                "face_type": "LIVE"
            },
            {
                "image": main_image,
                "image_type": "BASE64",
                "face_type": "LIVE",
                "face_token": face['face_token']
            }
        ])
        
        if result['error_code'] == 0:
            score = result['result']['score']
            if score > 80:  
                print(f"找到匹配人脸，相似度：{score}")
                return True
    return False

if __name__ == "__main__":
    x=0
    t_f = image_to_base64(r"5.21\1.jpg")  # 目标人物
    s=os.listdir('./5.21/素材')   #检索文件夹
    for i in s:
        g_f = image_to_base64(f"5.21/素材/{i}")
        if face_match(g_f, t_f):
            x+=1
            os.rename(f'5.21/素材/' + i, f'5.21/temp/第{x}个.jpg')
